
#import "MixController.h"

@implementation MixController

- appDidInit:sender
{
  sndOut = [[NXSoundOut alloc] init];
  if (!sndOut)
  {  fprintf(stderr, "Unable to get sound out device.  Bye!\n");
     return nil;
  }
  [sndOut setReserved:YES];
  snd1Stream = [[NXPlayStream alloc] initOnDevice:sndOut];
  snd2Stream = [[NXPlayStream alloc] initOnDevice:sndOut];
  tag = 1;
  return self;
}

- play:sender
{
  void          *snd1Data, *snd2Data;
  unsigned int  snd1Bytes, snd2Bytes;
  int           snd1Tag, snd2Tag, ret1, ret2;
  unsigned int  snd1ChannelCount, snd2ChannelCount;
  double        snd1Rate, snd2Rate;


  [self setSound1Name:snd1Text];
  [self setSound2Name:snd2Text];

  if ((!snd1) || (!snd2))
  { return self;
  }

  // snd1
  snd1Data = (void *)[snd1 data];
  snd1Bytes = (unsigned int)[snd1 dataSize];
  snd1Tag = tag++;
  snd1ChannelCount = [snd1 channelCount];
  if (([snd1 samplingRate] != SND_RATE_LOW) && ([snd1 samplingRate] != SND_RATE_HIGH))
  {  [snd1 convertToFormat:SND_FORMAT_LINEAR_16 
           samplingRate:SND_RATE_LOW
           channelCount:snd1ChannelCount
     ];
  }
  snd1Rate = [snd1 samplingRate];
  if ([snd1 dataFormat] != SND_FORMAT_LINEAR_16)
  {  [snd1 convertToFormat:SND_FORMAT_LINEAR_16];
  }
  // snd2
  snd2Data = (void *)[snd2 data];
  snd2Bytes = (unsigned int)[snd2 dataSize];
  snd2Tag = tag;
  snd2ChannelCount = [snd2 channelCount];
  if (([snd2 samplingRate] != SND_RATE_LOW) && ([snd2 samplingRate] != SND_RATE_HIGH))
  {  [snd2 convertToFormat:SND_FORMAT_LINEAR_16 
           samplingRate:SND_RATE_LOW
           channelCount:snd2ChannelCount
     ];
  }
  snd2Rate = [snd2 samplingRate];
  if ([snd2 dataFormat] != SND_FORMAT_LINEAR_16)
  {  [snd2 convertToFormat:SND_FORMAT_LINEAR_16];
  }

  // activate!
  [snd1Stream activate];
  [snd2Stream activate];

  ret1 = [snd1Stream playBuffer:snd1Data size:snd1Bytes tag:snd1Tag channelCount:snd1ChannelCount samplingRate:(float)snd1Rate];
  ret2 = [snd2Stream playBuffer:snd2Data size:snd2Bytes tag:snd2Tag channelCount:snd2ChannelCount samplingRate:(float)snd2Rate];

  fprintf(stderr, "ret1 == %d ret2 == %d\n", ret1, ret2);

  // I really should deactivate these precious resources, but you
  // shouldn't deactivate until you're sure the whole sound has been
  // played.  Since this is supposed to be a wicked simple example,
  // I'll leave that for later. 

  return self;
}

- setSound1Name:sender
{
  if (snd1)
  {  [snd1 free];
  }
  snd1 = [[Sound alloc] initFromSoundfile:[sender stringValue]];
  return self;
}

- setSound2Name:sender
{
  if (snd2)
  {  [snd2 free];
  }
  snd2 = [[Sound alloc] initFromSoundfile:[sender stringValue]];
  return self;
}


@end
